import { DynamicAtlasManager, SpriteFrame } from "cc";
import { GLoader } from "db://fairygui-xforge/GLoader";

let _cachedRemoteSpriteFrames = new Map<string, SpriteFrame>();

function isRemoteUrl(url: string): boolean {
    return url.startsWith("http://") || url.startsWith("https://");
}

let proto = GLoader.prototype as any;
const _origin_onExternalLoadSuccess = proto.onExternalLoadSuccess;
proto.onExternalLoadSuccess = function (frame: SpriteFrame) {
    if (frame && DynamicAtlasManager.instance.enabled && isRemoteUrl(this._url)) {
        const result = DynamicAtlasManager.instance.insertSpriteFrame(frame);
        if (result) {
            _cachedRemoteSpriteFrames.set(this._url, frame);
        }
    }
    _origin_onExternalLoadSuccess.call(this, frame);
}

const _origin_loadExternal = proto.loadExternal;
proto.loadExternal = function () {
    if (DynamicAtlasManager.instance.enabled && isRemoteUrl(this._url)) {
        const cachedFrame = _cachedRemoteSpriteFrames.get(this._url);
        if (cachedFrame) {
            if (cachedFrame.texture && cachedFrame.texture.isValid) {
                _origin_onExternalLoadSuccess.call(this, cachedFrame);
                return;
            } else {
                _cachedRemoteSpriteFrames.delete(this._url);
            }
        }
    }
    _origin_loadExternal.call(this);
}
